package com.lk.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lk.entity.Employee;
import com.lk.service.EmployeeService;
import com.lk.util.Const;
import com.lk.util.DateUtil;
import com.lk.util.PKUtil;

public class EmployeeServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	public void service(HttpServletRequest request,HttpServletResponse response)
				throws IOException,ServletException {
		String method = request.getParameter("_es");
		
		if("new_em".equals(method)){
			new_em(request,response);
		} else if("save".equals(method)){
			save(request,response);
		} else if("exit".equals(method)){
			exit(request,response);
		}
	}

	private void exit(HttpServletRequest request, HttpServletResponse response) 
			throws IOException,ServletException {
		HttpSession session = request.getSession();
		session.invalidate();
		response.sendRedirect("index.jspx");
	}

	private void save(HttpServletRequest request, HttpServletResponse response)
				throws IOException,ServletException {
		String name = request.getParameter("employee-name");
		String pwd = request.getParameter("employee-pwd");
		
		System.out.println("name: " + name + "\tpwd: " + pwd);
		Employee e = new Employee();
		EmployeeService es = new EmployeeService();
		e.setId(PKUtil.getPK());
		e.setLoginTime(DateUtil.getDate());
		e.setUsername(name);
		e.setPassword(pwd);
		es.save(e);
		
		HttpSession session = request.getSession();
		session.setAttribute(Const.USER_IN_SESSION,e);
		request.getRequestDispatcher("/WEB-INF/views/main.jsp").forward(request, response);
	}

	private void new_em(HttpServletRequest request, HttpServletResponse response)
				throws IOException,ServletException {
		request.getRequestDispatcher("/WEB-INF/views/new_employee.jsp").forward(request, response);
	}
}
